/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Filters
{
	using System;
	using System.Configuration;
	using Castle.MonoRail.Framework;
	using GearBlog.Web.ConfigSections;
	using GearBlog.Web.Models;
	using GearBlog.Web.Utils;

	public class AuthenticationFilterAttribute:FilterAttribute
    {
        private string[] _allowedRoles;
    	private Type _authenticationAgentType;
    	private bool _requiresLogin = false;

    	public AuthenticationFilterAttribute(Type authenticateAgentType):base(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter))
        {
    		_authenticationAgentType = authenticateAgentType;

        }
        public AuthenticationFilterAttribute(Type authenticateAgentType, params string[] allowedRoles):this(authenticateAgentType) 
        {
            _allowedRoles = allowedRoles;
        }
        
        public string[] AllowedRoles
        {
            get { return _allowedRoles; }
        }

    	public Type AuthenticationAgentType
    	{
    		get { return _authenticationAgentType; }
    		set { _authenticationAgentType = value; }
    	}

    	public bool RequiresLogin
    	{
			get { return _requiresLogin; }
			set { _requiresLogin = value; }
    	}
    }
    /// <summary>
    /// Summary description for AuthenticationFilter
    /// </summary>
    public class AuthenticationFilter:Filter,IFilterAttributeAware
    {
        private AuthenticationFilterAttribute _attribute;
        #region IFilterAttributeAware Members

        public FilterAttribute Filter
        {
            set { _attribute = (AuthenticationFilterAttribute)value; }
        }

        #endregion
        protected override bool OnBeforeAction(IRailsEngineContext context, Controller controller)
        {
			if (_attribute.AuthenticationAgentType != null) SecurityUtil.SetAuthenticationAgent(_attribute.AuthenticationAgentType);
            User user = SecurityUtil.GetCurrentUser(context);
        	context.CurrentUser = user;

        	bool isPermitted = !_attribute.RequiresLogin;

			MembershipManagerSection membershipManagerSection =
				(MembershipManagerSection)ConfigurationManager.GetSection("MembershipManager");

			if (!isPermitted)
			{
				if (user == null ||
				    !user.IsAuthenticated) //Redirect to Login
				{
					//Auto Login if feature is enabled- to save some development hassle
					AutoLoginElement autoLogin = membershipManagerSection.AutoLogin;
					if (autoLogin != null && autoLogin.Enabled)
						isPermitted = SecurityUtil.Authenticate(controller, autoLogin.UserName, autoLogin.Password, false, context.Url);
					else
						isPermitted = SecurityUtil.AttemptLogin(controller, context.Url);
				}
				else
				{
					if (this._attribute.AllowedRoles != null)
					{
						foreach (string allowedRole in this._attribute.AllowedRoles)
							isPermitted = isPermitted || (user.IsInRole(allowedRole));
					}
					else
						isPermitted = true;

					if (!isPermitted)
						OnAccessDenied(controller);
				}
			}
        	if (isPermitted && user!=null)
				controller.PropertyBag["CurrentUser"] = user;

			return isPermitted;
        }
		
		public virtual void OnAccessDenied(Controller controller)
		{
			SecurityUtil.ShowAccessDenied(controller);
		}
        private string BuildUrl(Controller controller, LinkElement link)
        {
            return controller.UrlBuilder.BuildUrl(controller.Context.UrlInfo, link.Controller, link.Action);
        }
    }
}
